<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_SealName_FormItem"
								prop="Entity.SealName"
								:rules="[{ required: true, message: '印章名称为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="印章名称" tooltip="印章的正式名称" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.SealName" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_SealCode_FormItem" prop="Entity.SealCode">
								<template #label>
									<WtmLabelTooltip label="印章编码" tooltip="印章的唯一编码" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.SealCode" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>公司信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_OrgId_FormItem" prop="Entity.OrgId">
								<template #label>
									<WtmLabelTooltip label="所属公司" tooltip="印章所属的公司" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.OrgId" clearable class="width100">
									<el-option v-for="item in stateData.AllSysOrgs" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>组织信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_GroupId_FormItem" prop="Entity.GroupId">
								<template #label>
									<WtmLabelTooltip label="所属组织" tooltip="印章所属的组织" />
								</template>
								<el-cascader
									:options="stateData.AllSysGroups"
									:props="{ checkStrictly: true, emitPath: false, label: 'Text', value: 'Value', children: 'Children' }"
									clearable
									filterable
									class="width100"
									v-model="stateData.vmModel.Entity.GroupId"
								/>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_SealType_FormItem"
								prop="Entity.SealType"
								:rules="[{ required: true, message: '印章类型为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="印章类型" tooltip="印章的类型分类" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.SealType" clearable class="width100">
									<el-option key="公章" value="公章" label="公章"></el-option>
									<el-option key="财务章" value="财务章" label="财务章"></el-option>
									<el-option key="合同章" value="合同章" label="合同章"></el-option>
									<el-option key="法人章" value="法人章" label="法人章"></el-option>
									<el-option key="部门章" value="部门章" label="部门章"></el-option>
									<el-option key="发票章" value="发票章" label="发票章"></el-option>
									<el-option key="人事章" value="人事章" label="人事章"></el-option>
									<el-option key="其他章" value="其他章" label="其他章"></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>印章生成</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" class="mb20">
							<el-form-item
								ref="Entity_SealImage_FormItem"
								prop="Entity.SealImage"
								:rules="[{ required: true, message: '印章需要点击生成按钮', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="印章图片" tooltip="使用印章生成器创建印章图片" />
								</template>
								<SealGenerator
									v-model="sealGeneratorData"
									:seal-name="stateData.vmModel.Entity.SealName"
									:seal-type="stateData.vmModel.Entity.SealType"
									@confirm="handleSealConfirm"
									@cancel="handleSealCancel"
								/>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>状态信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_Status_FormItem"
								prop="Entity.Status"
								:rules="[{ required: true, message: '印章状态为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="印章状态" tooltip="印章的当前状态" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.Status" clearable class="width100">
									<el-option key="正常" value="正常" label="正常"></el-option>
									<el-option key="停用" value="停用" label="停用"></el-option>
									<el-option key="作废" value="作废" label="作废"></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>使用信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_UseCount_FormItem"
								prop="Entity.UseCount"
								:rules="[{ required: true, message: '使用次数为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="使用次数" tooltip="印章的累计使用次数" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.UseCount" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_LastUseTime_FormItem" prop="Entity.LastUseTime">
								<template #label>
									<WtmLabelTooltip label="最后使用时间" tooltip="印章最后使用的时间" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.LastUseTime" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>其他信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remarks_FormItem" prop="Entity.Remarks">
								<template #label>
									<WtmLabelTooltip label="备注信息" tooltip="印章的备注信息" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remarks" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysSealApi as api } from '/@/views/common/sysseal/api';
import other from '/@/utils/other';
import { ISysSealVm } from '/@/views/common/sysseal/api/interface';
import { IViewModel } from '/@/types/common';
import SealGenerator from '/@/components/sealGenerator/index.vue';

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);
const stateData = reactive<IViewModel<ISysSealVm>>({
	vmModel: {
		Entity: {
			SealName: null,
			SealCode: null,
			OrgId: null,
			GroupId: null,
			SealType: '公章',
			SealImage: null,
			Status: '正常',
			UseCount: 0,
			LastUseTime: null,
			Remarks: null,
		},
		ActionName: null,
		IsMyApprove: null,
	},
	AllSysOrgs: [],
	AllSysGroups: [],
});

const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});

// 印章生成器数据 - 简化版本，只保留必要字段
const sealGeneratorData = ref({
	name: '圆形印章',
	type: 'chinese' as 'chinese' | 'bilingual',
	companyName: '',
	sealText: '',
	imageData: '',
});

// 印章生成器确认事件
const handleSealConfirm = (sealData: any) => {
	stateData.vmModel.Entity.SealImage = sealData.imageData;
	ElMessage.success('印章生成成功！');
};

// 印章生成器取消事件
const handleSealCancel = () => {
	// 可以在这里添加取消逻辑
};
const handleApiResponse = (response: any) => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	emit('refresh');
	loading.value = false;
	closeDialog();
};

const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response))
				.catch(handleError);
		}
	});
};
// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {},
		false
	);
};

// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
		other.getSelectList('/api/SysSeal/GetSysOrgs', [], false).then((x) => (stateData.AllSysOrgs = x)),
		other.getSelectList('/api/Common/GetGroups', [], false).then((x) => (stateData.AllSysGroups = x)),
	]);
};

const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}

	// 初始化印章生成器数据
	if (stateData.vmModel.Entity.SealName) {
		sealGeneratorData.value.companyName = stateData.vmModel.Entity.SealName;
	}
	if (stateData.vmModel.Entity.SealType) {
		// 根据印章类型设置章名
		switch (stateData.vmModel.Entity.SealType) {
			case '公章':
				sealGeneratorData.value.sealText = '公章';
				break;
			case '财务章':
				sealGeneratorData.value.sealText = '财务专用章';
				break;
			case '合同章':
				sealGeneratorData.value.sealText = '合同专用章';
				break;
			case '法人章':
				sealGeneratorData.value.sealText = '法人章';
				break;
			case '部门章':
				sealGeneratorData.value.sealText = '部门章';
				break;
			case '发票章':
				sealGeneratorData.value.sealText = '发票专用章';
				break;
			case '人事章':
				sealGeneratorData.value.sealText = '人事专用章';
				break;
			case '其他章':
				sealGeneratorData.value.sealText = '专用章';
				break;
			default:
				sealGeneratorData.value.sealText = '专用章';
		}
	}
	if (stateData.vmModel.Entity.SealImage) {
		sealGeneratorData.value.imageData = stateData.vmModel.Entity.SealImage;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSave,
			visible: true,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>

<style scoped></style>
